package com.cangshi.controller;

import com.cangshi.entity.*;
import com.cangshi.permission.entity.UserSubject;
import com.cangshi.permission.saver.SubjectHolder;
import com.cangshi.service.TaskConditionService;
import com.cangshi.service.TaskPositionService;
import com.cangshi.service.TaskService;
import com.cangshi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;


/**
 * Created by 15c on 2017/4/5.
 */
@Controller
@RequestMapping("/tasks")
public class TaskController {
    @Autowired
    TaskService taskService;
    @Autowired
    TaskPositionService taskPositionService;
    @Autowired
    TaskConditionService taskConditionService;
    @Autowired
    UserService userService;

    /**
     * 用于发布任务
     *
     * @param task 任务对象
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/details/create", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    String createNewTask(@RequestBody(required = false) TaskAndedPositionAndedTaskCondition task
    ) {
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();
        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();


        if (null == task) {
            throw new JSONException(100, "参数为空");
        }
        if (null == task.getPositionX() || null == task.getPositonY() || null == task.getTaskType()) {
            throw new JSONException(101, "参数不完整，缺少坐标或任务类型");
        }
        // ||null==task.getTaskContactInfo()最后需添加
        if (null == task.getTaskContent() || null == task.getTaskTitle() || null == task.getTaskMoney()) {
            throw new JSONException(102, "任务内容，任务联系人或任务标题或任务金额为空");
        }
//        判断此时登录的用户id是否等于任务创建者id，从而判断是否有权限发布任务
//        if (userId != task.getTaskCreator()) {
//            throw new JSONException(108, "taskCreator 的值与所登录用户不匹配，不具备发布任务权限");
//        }
        task.setTaskCreator(userId);
        int result = taskService.addTask(task);
        if (result != 1) {
            throw new JSONException(205, "任务发布失败，请重试");
        }
        //获得上次insert的id
        int taskId = taskService.getLastTaskId();
        //插入taskPositionService数据
        TaskPosition taskPosition = new TaskPosition();
        taskPosition.setPositionIp(task.getPositionIp());
        taskPosition.setPositionX(task.getPositionX());
        taskPosition.setPositonY(task.getPositonY());
        taskPosition.settTaskTaskId(taskId);
        int resultPosition = taskPositionService.insertXandY(taskPosition);
        if (1 != resultPosition) {
            taskService.deleteTask(taskId);
            throw new JSONException(206, "任务坐标保存失败，请重试");
        }
        TaskCondition taskCondition = new TaskCondition();
        taskCondition.setConditionMaxAge(task.getConditionMaxAge());
        taskCondition.setConditionMinAge(task.getConditionMinAge());
        taskCondition.setConditionSex(task.getConditionSex());
        taskCondition.setConditionUserMaxCredit(task.getConditionUserMaxCredit());
        taskCondition.setConditionUserMinCredit(task.getConditionUserMinCredit());
        taskCondition.setConditionUserMaxLevel(task.getConditionUserMaxLevel());
        taskCondition.setConditionUserMinLevel(task.getConditionUserMinLevel());
        taskCondition.settTaskTaskId(taskId);
        int resultCondition = taskConditionService.insertTaskCondition(taskCondition);
        if (1 != resultCondition) {

            taskPositionService.delete(taskId);
            taskService.deleteTask(taskId);

            throw new JSONException(206, "任务条件保存失败，请重试");
        }
        return new CorrectJSONObject("任务发布成功").toString();
    }

    /**
     * 通过taskId删除用户历史任务
     */
    @ResponseBody
    @RequestMapping(value = "/details/delete", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    String deleteTask(@RequestParam(required = false) Integer taskId) {

        if (null == taskId) {
            throw new JSONException(100, "参数为空");
        }
        int resultPosition = taskPositionService.delete(taskId);
        int resultCondition = taskConditionService.delete(taskId);
        int result = taskService.deleteTask(taskId);
        if (1 != result || 1 != resultCondition || 1 != resultPosition) {
            throw new JSONException(202, "任务删除失败");
        }
        return new CorrectJSONObject("任务删除成功").toString();
    }

    /**
     * 返回用户自己历史任务总页数
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/details/showTotal", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showHistoryTasksTotal() {
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();
        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        //一页的信息条数
        int pageSize = 20;
        //获得总页数
        int allTaskNum = taskService.selectOneUserAllHistoryTask(userId);
        int resultAllPage = allTaskNum / pageSize;
        int resultRemainder = allTaskNum % pageSize;
        if (0 < resultRemainder) {
            resultAllPage = resultAllPage + 1;
        }
        CorrectJSONObject correctJSONObject = new CorrectJSONObject("获取总页数成功");
        correctJSONObject.setData(resultAllPage);
        return correctJSONObject.toString();
    }

    /**
     * 通过用户Id查询用户自己历史任务记录分页显示
     *
     * @param page 请求第几页
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/details/show", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showHistoryTasks(@RequestParam(required = false) Integer page) {
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();
        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        //一页的信息条数
        int pageSize = 20;
        //获得总页数
        int allTaskNum = taskService.selectOneUserAllHistoryTask(userId);
        int resultAllPage = allTaskNum / pageSize;
        int resultRemainder = allTaskNum % pageSize;
        if (0 < resultRemainder) {
            resultAllPage = resultAllPage + 1;
        }
        if (null == page) {
            throw new JSONException(100, "参数为空");
        }
        if (0 >= page) {
            throw new JSONException(102, "page参数不可为负");
        }
        if (resultAllPage < page) {
            throw new JSONException(110, "请求页数超额");
        }
        //从那一条开始请求
        int startPos = pageSize * page - pageSize;
        List<Task> resultTask = taskService.selectUserCreateHistoryTaskBYUserId(startPos, pageSize, userId);
        if (null == resultTask) {
            throw new JSONException(200, "数据异常");
        }
        CorrectJSONObject object = new CorrectJSONObject("获取历史任务信息成功");
        object.setData(resultTask);
        object.put("allPage", resultAllPage);
        return object.toString();

    }

    /**
     * 新加功能
     * 访问别人的历史任务记录分页显示
     *
     * @param page 请求第几页
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/showOtherUserHistoryTask", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showOtherHistoryTasks(@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer userId) {
        //一页的信息条数
        int pageSize = 20;
        //获得总页数
        //获得总页数
        int allTaskNum = taskService.selectOneUserAllHistoryTask(userId);
        int resultAllPage = allTaskNum / pageSize;
        int resultRemainder = allTaskNum % pageSize;
        if (0 < resultRemainder) {
            resultAllPage = resultAllPage + 1;
        }
        if (null == page || null == userId) {
            throw new JSONException(100, "page或userId参数为空");
        }
        if (0 >= page) {
            throw new JSONException(102, "page参数不可为负");
        }
        if (resultAllPage < page) {
            throw new JSONException(110, "请求页数超额");
        }
        //从那一条开始请求
        int startPos = pageSize * page - pageSize;
        List<Task> resultTask = taskService.selectUserCreateHistoryTaskBYUserId(startPos, pageSize, userId);
        if (null == resultTask) {
            throw new JSONException(200, "数据异常");
        }
        CorrectJSONObject object = new CorrectJSONObject("获取历史任务信息成功");
        object.setData(resultTask);
        object.put("allPage", resultAllPage);
        return object.toString();
    }


    /**
     * 通过taskId 查询一个任务的详细信息
     *
     * @param taskId 任务Id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/detailedInfo", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showOneTaskDetailsInfo(@RequestParam(required = false) Integer taskId) {
        if (taskId == null) {
            throw new JSONException(100, "参数为空");
        }
        Task task;
        task = taskService.selectTaskDetails(taskId);
        if (null == task) {
            throw new JSONException(200, "数据异常");
        }
        CorrectJSONObject object = new CorrectJSONObject("获取历史任务信息成功");
        object.setData(task);
        return object.toString();
    }

    /**
     * 展示所有任务类型
     */

    @ResponseBody
    @RequestMapping(value = "showAllTaskType", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String showAllTaskType() {
        List<TaskType> list = taskService.selectAllType();
        if (null == list) {
            throw new JSONException(200, "获取数据失败");
        }
        CorrectJSONObject object = new CorrectJSONObject("获取所有的任务类型成功");
        object.setData(list);
        return object.toString();
    }

    /**
     * 用户条件性选筛选任务总页数
     */
    @ResponseBody
    @RequestMapping(value = "/search/classificationTotal", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String taskClassificationByTaskTypeTotal(@RequestParam(required = false) Integer taskType,
                                             @RequestParam(required = false) Double minPrice,
                                             @RequestParam(required = false) Double maxPrice,
                                             @RequestParam(required = false) Double x,
                                             @RequestParam(required = false) Double y,
                                             @RequestParam(required = false) Integer distance,
                                             @RequestParam(required = false) String keyword) {
        if (null == x || null == y) {
            throw new JSONException(100, "缺少经纬度关键参数");
        }
        if (null == distance) {
            distance = 1500000000;
        }
        //一次查询个数
        int pageSize = 20;
        //获取筛选任务的总页数
        int allTaskNum = taskService.selectAllNumber(minPrice, maxPrice, taskType, distance, keyword, x, y);
        int resulAllPage = allTaskNum / pageSize;
        int resultRemainder = allTaskNum % pageSize;
        if (0 < resultRemainder) {
            resulAllPage = resulAllPage + 1;
        }
        CorrectJSONObject object = new CorrectJSONObject("任务总页数");
        object.setData(resulAllPage);
        return object.toString();
    }

    /**
     * 修改功能
     * 用户条件性选筛选任务
     *
     * @param taskType 任务类型
     * @param minPrice 任务最低价
     * @param maxPrice 任务最高价
     * @param x        纬度
     * @param y        经度
     * @param distance 距离
     * @param keyword  关键字
     * @param page     请求第几页
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/search/classification", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String taskClassificationByTaskType(@RequestParam(required = false) Integer taskType,
                                        @RequestParam(required = false) Double minPrice,
                                        @RequestParam(required = false) Double maxPrice,
                                        @RequestParam(required = false) Double x,
                                        @RequestParam(required = false) Double y,
                                        @RequestParam(required = false) Integer distance,
                                        @RequestParam(required = false) String keyword,
                                        @RequestParam(required = false) Integer page

    ) {
        //一次查询个数
        int pageSize = 20;
        if (null == x || null == y || null == page) {
            throw new JSONException(100, "x或y或请求页数参数为空");
        }

        if (null == distance) {
            distance = 1500000000;
        }
        //获取当前登录对象（判断用户是否登陆）
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();
        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //用户为登陆状态时的条件性选筛选(如果当前有用户登录)
        if (null != userEntity) {
            //获取当前的用户登录id
            int userId = userEntity.getUserId();
           User user= userService.selectAllUserInfoByUserId(userId);
            //获得用户生日
            Date birthday=user.getUserBirthday();
            Integer year_old;
            if (null!=birthday){
                //获得当前时间
                Date today= new Date();
                //获得用户当前年龄
                year_old=today.getYear()-birthday.getYear();
            }else {
                year_old= null;
            }
            int allTaskNum = taskService.selectTaskNumByLandUser(minPrice, maxPrice, taskType, distance, keyword, x, y, user.getUserSex(), year_old);
            int resulAllPage = allTaskNum / pageSize;
            int resultRemainder = allTaskNum % pageSize;
            if (0 < resultRemainder) {
                resulAllPage = resulAllPage + 1;
            }
            System.out.print("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<登录后任务总条数++++"+allTaskNum);
            if (resulAllPage < page) {
                throw new JSONException(110, "请求页数超额");
            }
            //从那一条开始请求
            int startPos = pageSize * page - pageSize;
            List<Task> taskList = taskService.selectTaskByLandUser(minPrice, maxPrice, taskType, distance, keyword, startPos, pageSize, x, y, user.getUserSex(),year_old);
            if (null == taskList) {
                throw new JSONException(200, "数据异常");
            }
            CorrectJSONObject object = new CorrectJSONObject("获取历史任务信息成功");
            object.setData(taskList);
            object.put("allPage", resulAllPage);
            return object.toString();
        }else {
            //用户未登录时的条件性选筛选
            //获取筛选任务的总页数

            int allTaskNum = taskService.selectAllNumber(minPrice, maxPrice, taskType, distance, keyword, x, y);
            int resulAllPage = allTaskNum / pageSize;
            int resultRemainder = allTaskNum % pageSize;
            if (0 < resultRemainder) {
                resulAllPage = resulAllPage + 1;
            }
            System.out.print("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<未登录任务总条数+++++ "+allTaskNum);
            if (resulAllPage < page) {
                throw new JSONException(110, "请求页数超额");
            }
            //从那一条开始请求
            int startPos = pageSize * page - pageSize;
            System.out.println("---------------->"+startPos+","+pageSize);
            List<Task> taskList = taskService.selectTaskByLandUser(minPrice, maxPrice, taskType, distance, keyword, startPos, pageSize, x, y,null,null);
            if (null == taskList) {
                throw new JSONException(200, "数据异常");
            }
            CorrectJSONObject object = new CorrectJSONObject("获取历史任务信息成功");
            object.setData(taskList);
            object.put("allPage", resulAllPage);
            return object.toString();
        }
    }

    /**
     * 查询用于主页显示的任务总页数
     */
    @ResponseBody
    @RequestMapping(value = "/homePageTotal", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String taskHomePageTotal() {
        //一页的信息条数
        int pageSize = 10;
        //获得总页数
        int allTaskNum = taskService.selectHomePageTaskNum();
        int resultAllPage = allTaskNum / pageSize;
        int resultRemainder = allTaskNum % pageSize;
        if (0 < resultRemainder) {
            resultAllPage = resultAllPage + 1;
        }
        CorrectJSONObject correctJSONObject = new CorrectJSONObject("获取总页数成功");
        correctJSONObject.setData(resultAllPage);
        return correctJSONObject.toString();

    }

    /**
     * 查询任务用于主页显示(分页显示)
     *
     * @param page 请求第几页
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/homePageTask", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String taskClassificationByTaskType(@RequestParam(required = false) Integer page) {
        //一次查询个数 10个
        int pageSize = 10;
        if (null == page) {
            throw new JSONException(100, "page参数为空");
        }
        //获取筛选任务的总页数
        int allTaskNum = taskService.selectHomePageTaskNum();
        int resulAllPage = allTaskNum / pageSize;
        int resultRemainder = allTaskNum % pageSize;
        if (0 < resultRemainder) {
            resulAllPage = resulAllPage + 1;
        }
        System.out.println("-------------->" + resulAllPage);
        if (resulAllPage < page) {
            throw new JSONException(110, "请求页数超额");
        }
        //从那一条开始请求
        int startPos = pageSize * page - pageSize;
        List<Task> taskList = taskService.selectHomePageTask(startPos, pageSize);
        if (null == taskList) {
            throw new JSONException(200, "数据异常");
        }
        CorrectJSONObject object = new CorrectJSONObject("获取历史任务信息成功");
        object.setData(taskList);
        object.put("allPage", resulAllPage);
        return object.toString();
    }

    /**
     * 用户修改自己创建的任务的状态
     *
     * @param taskId    任务Id
     * @param taskState 任务修改后的状态
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/details/taskStateRevise", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    String taskStateRevise(@RequestParam(required = false) Integer taskId,
                           @RequestParam(required = false) Integer taskState) {
        // 获取当前访问对象
        UserSubject subject = (UserSubject) SubjectHolder.getSubject();
        //获取当前的登录信息
        UserEntity userEntity = (UserEntity) subject.getAuthorizationEntity();
        //获取当前的用户登录id
        int userId = userEntity.getUserId();
        if (null == taskId || null == taskState) {
            throw new JSONException(100, "taskId或taskState参数为空");
        }
        int result = taskService.updateTaskState(taskId, userId, taskState);
        if (1 != result) {
            throw new JSONException(200, "修改任务状态失败");
        }
        return new CorrectJSONObject("任务状态修改成功").toString();
    }

    /**
     * 用于同时删除对个任务
     *
     * @param tasks task对象数组
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/details/someTaskDelete", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    String deleteSomeTask(@RequestBody(required = false) Task[] tasks) {
        if (null == tasks) {
            throw new JSONException(100, "tasks参数为空");
        }
        for (Task task : tasks) {
            if (null == task) {
                throw new JSONException(101, "任务数组对象中存在空元素，请检查");
            }
            if (null == task.getTaskId()) {
                throw new JSONException(103, "任务数组对象中有对象的Id不存在，请检查");
            }
            int resultPosition = taskPositionService.delete(task.getTaskId());
            int resultCondition = taskConditionService.delete(task.getTaskId());
            int result = taskService.deleteTask(task.getTaskId());
            if (1 != result || 1 != resultCondition || 1 != resultPosition) {

                throw new JSONException(202, "任务删除失败");

            }

        }

        return new CorrectJSONObject("任务删除成功").toString();
    }
}
